<template>
    <div class="study-rewards">
        <h3 align="center">奖学金</h3>
        <!-- 第一行卡片 -->
        <el-row justify="center">
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <img src="@/assets/scholarship1.png" class="image" />
                    <el-statistic
                        title="获奖学金（次）"
                        :value="awardCount"
                        class="demo-class"
                        :value-style="{ color: '#B377EA' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <img src="@/assets/scholarship2.png" class="image" />
                    <el-statistic
                        title="累计获奖学金（元）"
                        :value="totalAmount"
                        class="demo-class"
                        :value-style="{ color: '#FF9935' }"
                    />
                </el-card>
            </el-col>
        </el-row>

        <!-- 第二行卡片 -->
        <el-row class="card-row">
            <template v-for="scholarshipGroup in _.chunk(scholarships, 3)">
                <el-col
                    :span="8"
                    v-for="(scholarship, index) in scholarshipGroup"
                    :key="index"
                    class="table-col scholarship-col-height"
                >
                    <el-card shadow="hover" class="scholarship-card">
                        <div class="title">{{ scholarship.name }}</div>
                        <div class="subtitle">金额:{{ scholarship.bonus }}元</div>
                        <div class="date">
                            <div class="day">{{ getYear(scholarship.date) }}</div>
                            <div class="day">{{ getDayMonth(scholarship.date) }}</div>
                        </div>
                    </el-card>
                    <el-card shadow="hover" class="bottom-card">{{ scholarship.level }}</el-card>
                </el-col>
            </template>
        </el-row>

        <h3 align="center">竞赛获奖</h3>
        <!-- 第一行卡片 -->
        <el-row class="competition-row">
            <el-col :span="16">
                <el-card shadow="hover" class="competition-card">
                    <img src="@/assets/competition.png" class="image" />
                    <el-statistic
                        title="获奖次数（次）"
                        :value="competitions.length"
                        class="demo-class"
                        :value-style="{ color: '#B377EA' }"
                    />
                </el-card>
            </el-col>
        </el-row>
        <!-- 第二行卡片 -->
        <el-row class="card-row">
            <template v-for="competitionGroup in _.chunk(competitions, 3)">
                <el-col :span="8" v-for="(competition, index) in competitionGroup" :key="index" class="table-col">
                    <el-card shadow="hover" class="competition-card">
                        <div class="title">{{ competition.name }}</div>
                        <img src="@/assets/rod.png" class="image2" />
                        <div class="date">
                            <div class="day">{{ getYear(competition.date) }}</div>
                            <div class="day">{{ getDayMonth(competition.date) }}</div>
                        </div>
                    </el-card>
                    <el-card shadow="hover" class="bottom-card-2">
                        <div class="bottom-card-content">
                            <span class="level">{{ competition.level }}</span>
                            <span class="department">{{ competition.department }}</span>
                        </div>
                    </el-card>
                </el-col>
            </template>
        </el-row>
        <h3 align="center">助学金</h3>
        <!-- 第一行卡片 -->
        <el-row justify="center">
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <img src="@/assets/stipend1.png" class="image" />
                    <el-statistic
                        title="获助学金(次)"
                        :value="allowanceCount"
                        class="demo-class"
                        :value-style="{ color: '#FF9935' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <img src="@/assets/stipend2.png" class="image" />
                    <el-statistic
                        title="累计获助学金(元)"
                        :value="totalAllowanceAmount"
                        class="demo-class"
                        :value-style="{ color: '#F06869' }"
                    />
                </el-card>
            </el-col>
        </el-row>

        <!-- 第二行卡片 -->
        <el-row v-show="allowanceCount !== 0" justify="center">
            <el-col :span="16">
                <el-card shadow="hover">
                    <el-table
                        :data="studyTableData"
                        ref="table"
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        height="450"
                        empty-text="暂无数据"
                        :loading="isStudiesLoading"
                    >
                        <el-table-column prop="name" label="助学金" />
                        <el-table-column prop="date" label="时间" />
                        <el-table-column prop="level" label="等级" />
                        <el-table-column prop="bonus" label="资助金额" />
                    </el-table>
                </el-card>
            </el-col>
        </el-row>
        <h3 align="center">助学贷</h3>
        <!-- 第一行卡片 -->
        <el-row justify="center">
            <el-col :span="8">
                <el-card shadow="hover" style="height: 100px; background-color: #f8fbfd">
                    <img src="@/assets/loan2.png" class="image1" />
                    <el-statistic
                        title="已发放金额(元):"
                        :value="receivedAmount"
                        class="demo-class-1"
                        :value-style="{ color: '#76BD5F' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="8" class="table-col-1">
                <el-card shadow="hover" style="height: 100px; background-color: #f8fbfd">
                    <img src="@/assets/loan3.png" class="image1" />
                    <el-statistic
                        title="已还本金(元):"
                        :value="repayAmount"
                        class="demo-class-1"
                        :value-style="{ color: '#B377EA' }"
                    />
                </el-card>
            </el-col>
        </el-row>
        <!-- 第二行卡片 -->
        <el-row v-show="receivedAmount !== 0" justify="center">
            <el-col :span="16">
                <el-card shadow="hover">
                    <el-table
                        :data="loanTableData"
                        ref="table"
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        height="450"
                        empty-text="暂无数据"
                        :loading="isLoansLoading"
                    >
                        <el-table-column prop="date" label="发放日期" />
                        <el-table-column prop="amount" label="金额" />
                    </el-table>
                </el-card>
            </el-col>
        </el-row>
        <h3 align="center">勤工助学</h3>
        <!-- 第一行卡片 -->
        <el-row justify="center">
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <img src="@/assets/work-study1.png" class="image" />
                    <el-statistic
                        title="参与岗位(项)"
                        :value="jobCount"
                        class="demo-class"
                        :value-style="{ color: '#B377EA' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <img src="@/assets/work-study2.png" class="image" />
                    <el-statistic
                        title="累计工时(小时)"
                        :value="totalJobHours"
                        class="demo-class"
                        :value-style="{ color: '#589CED' }"
                    />
                </el-card>
            </el-col>
        </el-row>

        <!-- 勤工助学工时年度分布柱状图 -->
        <el-row v-if="totalJobHours !== 0" justify="center">
            <el-col :span="16">
                <el-card shadow="hover">
                    <div class="biaoti">勤工助学工时年度分布图</div>
                    <div id="jobHoursHistogram"></div>
                </el-card>
            </el-col>
        </el-row>
        <h3 align="center">惩处信息</h3>
        <!-- 第一行卡片 -->
        <el-row justify="center">
            <el-col :span="4">
                <el-card shadow="hover" style="height: 130px">
                    <img src="@/assets/admonish.png" class="image3" />
                    <el-statistic
                        title="警告"
                        :value="admonishCount"
                        suffix="次"
                        class="demo-class-3"
                        :value-style="{ color: '#FF9935' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="4">
                <el-card shadow="hover" style="height: 130px">
                    <img src="@/assets/record.png" class="image3" />
                    <el-statistic
                        title="记过"
                        :value="recordCount"
                        suffix="次"
                        class="demo-class-3"
                        :value-style="{ color: '#76BD5F' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="4">
                <el-card shadow="hover" style="height: 130px">
                    <img src="@/assets/warning.png" class="image3" />
                    <el-statistic
                        title="严重警告"
                        :value="warningCount"
                        suffix="次"
                        class="demo-class-3"
                        :value-style="{ color: '#B377EA' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="4">
                <el-card shadow="hover" style="height: 130px">
                    <img src="@/assets/scan.png" class="image3" />
                    <el-statistic
                        title="留校察看"
                        :value="scanCount"
                        suffix="次"
                        class="demo-class-3"
                        :value-style="{ color: '#589CED' }"
                    />
                </el-card>
            </el-col>
        </el-row>

        <!-- 第四行卡片 -->
        <el-row v-show="punishmentTableData.length !== 0" justify="center">
            <el-col :span="16">
                <el-card shadow="hover">
                    <el-table
                        :data="punishmentTableData"
                        ref="table"
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        height="450"
                        empty-text="暂无数据"
                        :loading="isPunishmentsLoading"
                    >
                        <el-table-column prop="date" label="惩处时间" />
                        <el-table-column prop="type" label="类型" />
                        <el-table-column prop="reason" label="原因" />
                    </el-table>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import * as echarts from 'echarts'
</script>
<script setup>
import api from '@/api/student'
import {ref, computed, onMounted, watch, nextTick} from 'vue'
import _ from 'lodash'

const props = defineProps({
    rewards: Object,
})

const scholarships = ref([])
const competitions = ref([])

const studyTableData = ref([])
const isStudiesLoading = ref(false)

const receivedAmount = ref(0)
const repayAmount = ref(0)
const loanTableData = ref([])
const isLoansLoading = ref(false)

const jobCount = ref(0)
const totalJobHours = ref(0)

const admonishCount = ref(0)
const recordCount = ref(0)
const warningCount = ref(0)
const scanCount = ref(0)
const punishmentTableData = ref([])
const isPunishmentsLoading = ref(false)

const fetchScholarships = async () => {
    try {
        const response = await api.getScholarships(props.rewards.id)
        scholarships.value = response.data
    } catch (err) {
        console.error(err)
    }
}

const fetchCompetitions = async () => {
    try {
        const response = await api.getCompetitions(props.rewards.id)
        competitions.value = response.data
        console.log(competitions.value)
    } catch (error) {
        console.error(error)
    }
}

const fetchAllowanceData = async () => {
    try {
        isStudiesLoading.value = true
        const response = await api.getAllowances(props.rewards.id)
        studyTableData.value = response.data

        console.log(studyTableData.value)
    } catch (error) {
        console.error(error)
    } finally {
        isStudiesLoading.value = false
    }
}

const fetchLoanData = async () => {
    try {
        isLoansLoading.value = true
        const response = await api.getLoan(props.rewards.id)
        loanTableData.value = response.data.loans
        receivedAmount.value = response.data.loans.reduce((total, item) => total + item.amount, 0)
        repayAmount.value = response.data.repayAmount

        console.log(loanTableData.value)
    } catch (error) {
        console.error(error)
    } finally {
        isLoansLoading.value = false
    }
}

const fetchJobData = async () => {
    try {
        const response = await api.getJob(props.rewards.id)
        jobCount.value = response.data.amount
        totalJobHours.value = response.data.jobTimes.reduce((total, item) => total + item.hours, 0)
        await nextTick(() => {
            drawJobHoursHistogram(response.data.jobTimes)
        })
        // drawJobHoursHistogram(response.data.jobTimes)
        console.log(jobCount.value)
    } catch (error) {
        console.error(error)
    }
}

const drawJobHoursHistogram = (data) => {
    const chartContainer = document.getElementById('jobHoursHistogram')
    const chart = echarts.init(chartContainer)

    if (data.length === 0) {
        chart.clear()
        chart.setOption({
            graphic: {
                type: 'text',
                left: 'center',
                top: 'middle',
                style: {
                    text: '暂无数据',
                    fill: '#999999',
                    fontSize: 14,
                },
            },
        })

        return
    }

    const years = data.map((item) => item.year)
    const hours = data.map((item) => item.hours)

    const options = {
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                const year = params[0].axisValue
                const hour = params[0].data

                return `年度：${year}<br>工时：${hour}`
            },
        },
        xAxis: {
            type: 'category',
            name: '年度',
            data: years,
        },
        yAxis: {
            type: 'value',
            name: '工时',
        },
        series: [
            {
                name: '工时',
                type: 'bar',
                data: hours,
            },
        ],
    }

    chart.setOption(options)
}

const fetchPunishmentsData = () => {
    isPunishmentsLoading.value = true
    api.getPunishments(props.rewards.id)
        .then((response) => {
            isPunishmentsLoading.value = false

            punishmentTableData.value = response.data

            admonishCount.value = calculatePunishmentCount(response.data, '警告')
            recordCount.value = calculatePunishmentCount(response.data, '记过')
            warningCount.value = calculatePunishmentCount(response.data, '严重警告')
            scanCount.value = calculatePunishmentCount(response.data, '留校察看')
        })
        .catch((error) => {
            isPunishmentsLoading.value = false
            console.error('Failed to fetch punishments data:', error)
        })
}

const calculatePunishmentCount = (data, type) => {
    return data.reduce((count, item) => {
        if (item.type === type) {
            return count + 1
        }

        return count
    }, 0)
}

const getYear = (dateStr) => {
    return dateStr.split('-')[0]
}

const getDayMonth = (dateStr) => {
    const [_, month, day] = dateStr.split('-')

    return `${month}.${day}`
}

const awardCount = computed(() => scholarships.value.length)

const totalAmount = computed(() => scholarships.value.reduce((total, scholarship) => total + scholarship.bonus, 0))

const allowanceCount = computed(() => studyTableData.value.length)
const totalAllowanceAmount = computed(() => studyTableData.value.reduce((total, item) => total + item.bonus, 0))

onMounted(async () => {
    if (!props.rewards.id) {
        return
    }
    await fetchData()
})

const fetchData = async () => {
    await fetchScholarships()
    await fetchCompetitions()
    await fetchAllowanceData()
    await fetchLoanData()
    await fetchJobData()
    await fetchPunishmentsData()
}

watch(
    () => props.rewards.id,
    async (newId, oldId) => {
        if (newId !== oldId) {
            await fetchData()
        }
    }
)
</script>
<style scoped>
.study-rewards {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0;
    background-color: #e8e8e8;
}

.el-row {
    width: 100%;
    margin: 0 0 5px 0;
}

.el-col {
    flex: 1;
    box-sizing: border-box;
    margin: 0;
}

.el-card {
    margin: 0;
}

.card-row {
    display: flex;
    flex-wrap: wrap;
    width: 69%;
    margin: 0;
    justify-content: flex-start;
}
.scholarship-col-height {
    height: 165px;
}
.table-col-1 {
    margin: 0 0 0 10px;
}
.scholarship-card {
    height: 136px;
    background-color: #f8fbfd;
}
.table-col {
    margin: 0 15px 5px 15px;
    flex: 0 0 calc(33.33% - 30px);
    position: relative;
}

.title {
    margin: 10px 0;
    font-size: 18px;
    font-weight: bold;
}

.subtitle {
    margin: 20px 0;
    font-size: 15px;
    color: grey;
}

.date {
    position: absolute;
    top: 20px;
    right: 20px;
    font-weight: bold;
    background-color: #579ced;
    color: white;
    padding: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.day {
    font-size: 14px;
    font-weight: bold;
    text-align: center;
}

.competition-row {
    margin-left: calc(33.33% - 5px);
}

.competition-card {
    height: 120px;
    background-color: #f8fbfd;
}

.bottom-card {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    position: relative;
    transform: translateY(-50%);
    font-size: 18px;
    text-align: center;
}

.bottom-card-2 {
    height: 80px;
    font-size: 18px;
}

.bottom-card-content {
    display: flex;
    justify-content: space-between;
    /* align-items: center; */
}
.level {
    text-align: left;
}

.department {
    text-align: right;
}

.image {
    position: relative;
    top: 13px;
    left: 80px;
    width: 60px;
    display: block;
}

.image1 {
    position: relative;
    left: 20px;
    width: 60px;
    display: block;
}

.image2 {
    width: 45px;
    display: block;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
}
.image3 {
    position: relative;
    top: 15px;
    left: 30px;
    width: 50px;
    display: block;
}

.demo-class {
    position: relative;
    top: -47px;
    left: 230px;
    width: 150px;
    /* border: solid red 1px; */
}

.demo-class-1 {
    position: relative;
    top: -55px;
    left: 120px;
    width: 120px;
}

.demo-class-2 {
    position: relative;
    top: 20px;
    left: 70px;
    width: 60px;
}
.demo-class-3 {
    position: relative;
    top: -35px;
    left: 120px;
    width: 100px;
}
.biaoti {
    font-size: 18px;
    font-weight: bold;
    color: #909399;
    text-align: center;
}

#jobHoursHistogram {
    margin: 0 auto;
    height: 390px;
}
</style>
